var HOST = 'http://'+location.host+'/atdd/';
var API = HOST+'web/api/index.php/';

function Plus(){
    //base64加密
    this.base64encode = function (str) {
        var encryptedHexStr = CryptoJS.enc.Utf8.parse(str);

        return CryptoJS.enc.Base64.stringify(encryptedHexStr);
    };
    //base64解密
    this.base64decode = function (str) {
        var words = CryptoJS.enc.Base64.parse(str);

        return words.toString(CryptoJS.enc.Utf8);
    };
    //获取url参数
    this.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return ''
    };
}
var plus = new Plus();

(function ($) {

    //跳转去登录
    window.toSignin = function (back,url) {
        var from = back || (location.pathname + location.search);

        var href = url || SITE_URL+'login' + (from ? ('?from=' + plus.base64encode(from)) : '');

        window.location.href = href;
    };

    //跳转页面
    window.toPage = function (str) {
        var form = plus.getUrlParam('from');

        if(!str) str = '';
        if(form){
            try {
                form = plus.base64decode(plus.getUrlParam('from'));
            }catch (e){
                form = SITE_URL+'welcome';
            }
        }

        var url =  '';

        if(str){
            url = SITE_URL + str;
        }else if(form){
            url = form;
        }else{
            url = SITE_URL+'welcome';
        }

        window.location.href = url;
    };

    //保存token
    window.setToken = function (rs) {

        var res = plus.base64encode(rs);
        Cookies.set('yesToken', res)
    };

    //获取token
    window.getToken = function () {
        var res = Cookies.get('yesToken');

        if (!res) return false;

        return plus.base64decode(res);
    };

    //清除token
    window.clearToken = function () {
        Cookies.remove('yesToken');
    };

    //保存用户信息
    window.setUser = function (rs) {
        Cookies.set('yes', plus.base64encode(JSON.stringify(rs)))
    };

    //不传参就是获取用户信息对象 传参获取单个用户信息
    window.getUser = function (rs) {
        var res = Cookies.get('yes');
        if (!res) {
            return false
        }
        return rs ? JSON.parse(plus.base64decode(res))[rs] : JSON.parse(plus.base64decode(res))
    };
    //清楚用户信息
    window.clearUser = function () {
        Cookies.remove('yes');
    };
    //更新用户信息
    window.editUser = function (rs, val) {
        var res = Cookies.get('yes');
        if (!res) {
            return false
        }
        var data = JSON.parse(plus.base64decode(res));
        data[rs] = val;
        $.putUser(data)
    };

    //倒计时
    window.countDown = function (item) {
        var t = 60;

        item.html(t + '秒后重发').removeClass('on');
        var timer = setInterval(function () {
            if (t == 0) {
                item.html('获取验证码').addClass('on');
                clearInterval(timer);
            } else {
                t--;
                item.html(t + '秒后重发');
            }
        }, 1000)

    };

    //检查是否登录，并且拼接head
    window.checkUser= function () {

        if (getToken()) {
            $.ajaxSetup({
                headers: {
                    token: getToken()
                }
            });
        } else {
            toSignin()
        }
    };

    //监听浏览器返回
    window.returnWin= function (fun) {
        window.addEventListener("popstate", function(e) {
            if(typeof fun === 'function') fun(e);
        }, false);
        history.pushState({},'','#')
    };

    //消息框
    window.msg = function (str, fun, time) {

        if(!time) time = 2;

        return layer.open({
            content: str,
            skin: 'msg',
            time: time,
            end: function(){
                if(typeof  fun === 'function') fun();
            }
        });
    };

    //加载动画
    window.load = {
        ind: null,
        show: function(){
            load.ind = layer.open({
                type: 2,
                // content: '加载中',
                shadeClose: false,
                shade: 'background-color: rgba(0,0,0,0.5)' //自定义遮罩的透明度
            });
        },
        hide: function () {
            layer.close(load.ind);
        }
    };

    /**
     * foreach
     */
    window.forE = function forE(arr,fun){
        if(arr){
            for (var i=0;i<arr.length;i++){
                (typeof fun=='function')&&fun(arr[i],i);
            }
        }else{
            return false;
        }
    };

    /*
     时间戳转换
     newDate.format('yyyy-MM-dd h:m:s');
     */
    window.Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    };

    /*
     分页加载
     */
    window.load_t = true;
    window.pageLoad = function(callback) {
        var loadBox = $('.load-move');
        var naveBox = $('.m-nave');

        $(window).on('scroll', function () {
            var scrollTop = $(this).scrollTop();
            var naveHeight = naveBox.height();
            var winHeight = $(window).height();

            if (!naveHeight) naveHeight = 0;

            if ((loadBox.offset().top + loadBox.innerHeight() / 2) <= (scrollTop + winHeight - naveHeight) && load_t && !loadBox.hasClass('not')) {
                load_t = false;

                callback();
            }
        });
        callback();
    };

    //根据接口返回 显示错误信息 或者 返回授权
    var msgT = 0;
    $(document).ajaxSuccess(function (event, xhr, settings) {
        if (xhr.responseText) {
            try {
                var res = JSON.parse(xhr.responseText);

                if(res.returnNo){
                    switch (res.returnNo){
                        case '-99':
                            if(!msgT){
                            	clearToken();
                                clearUser();
                                msg(res.returnInfo, function(){
                                    toSignin();
                                });
                            }
                            msgT ++;
                            break;
                        default:
                            if(res.returnNo!='0000'&&res.returnNo!='0051') msg(res.returnInfo);
                            break;
                    }
                }
            } catch (e){

            }
        }
    });

})(jQuery);
